package com.example.demo.bizhan.distributelock.service;

import com.example.demo.bizhan.distributelock.util.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static java.lang.System.out;

/**
 * @description: xxx
 * @time: 2020/11/2 11:11
 * @author: baojinlong
 **/
@Service
@Slf4j
public class PayService {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private ItemsService itemsService;
    @Autowired
    private DistributedLock distributedLock;

    public boolean buy(String itemId) {
        // 购买的个数
        int buyCount = 9;
        // 判断库存
        int itemsCounts = itemsService.getItemsCounts(itemId);
        if (itemsCounts < 9) {
            log.error("库存不足,下单失败,购买数{}件,库存只有{}件", buyCount, itemsCounts);
            return false;
        }
        // 订单
        boolean flag = ordersService.save(itemId);
        // 模拟高并发场景
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            out.println("并发异常");
        }


        // 扣库存
        if (flag) {
            itemsService.reduceCount(itemId, buyCount);
        } else {
            log.error("订单创建失败......");
            return false;
        }
        return true;
    }


    /**
     * 增加分布式锁的改进方法
     *
     * @param itemId
     * @return
     */
    public boolean buy2(String itemId) {
        // 获取锁
        distributedLock.getLock();

        // 购买的个数
        int buyCount = 9;
        // 判断库存
        int itemsCounts = itemsService.getItemsCounts(itemId);
        if (itemsCounts < 9) {
            log.error("库存不足,下单失败,购买数{}件,库存只有{}件", buyCount, itemsCounts);
            distributedLock.releaseLock();
            return false;
        }
        // 订单
        boolean flag = ordersService.save(itemId);
        // 模拟高并发场景
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            distributedLock.releaseLock();
            out.println("并发异常");
        }


        // 扣库存
        if (flag) {
            itemsService.reduceCount(itemId, buyCount);
            distributedLock.releaseLock();
        } else {
            log.error("订单创建失败......");
            distributedLock.releaseLock();
            return false;
        }
        return true;
    }
}
